// pages/user/user.js
var app = getApp();

let fetch = require('../../utils/fetch');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    waitingList: [],
    doctorTabArr: {
      curHdIndex: '1',
      curBdIndex: '1'
    },
    tabNumber: {
      one: 0,
      two: 0,
      three: 0
    },

    dialogueHeight: 0,
    userMsg: [],
    inputMsg: "",
    userId: "",
    userStatus: "",
    showImgAddBox: true,
    showDialogue: true,
    allTempFilePaths: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });

    const that = this;

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          dialogueHeight: res.windowHeight
        })
      },
    })

    //用户信息
    fetch("inquiryDoctor/" + app.loginUser.id + '/isOrRegister').then(res => {
      app.userIMinfo = res.data.data;
      //极光初始化
      this.initJim().then(x => {
        //极光登录
        JIM.login({
          'username': app.userIMinfo.imUsername,
          'password': app.userIMinfo.imPassword,
          'is_md5': true
        }).onSuccess(function (data) {

          //获取用户信息列表
          JIM.getConversation().onSuccess(function (data) {

            
          }).onFail(function (data) {
            wx.showToast({
              title: '请求超时',
              icon: 'fail',
              duration: 1500
            })
          });

          //监听实时会话信息
          JIM.onMsgReceive(function (data) {
            console.log(data.messages)
            if (data.messages.length > 0) {
              that.setMsgBox(that.data.userId, data.messages);
            }
          });

          //监听离线新消息
          JIM.onSyncConversation(function (data) {
            if (data.length >= 1) {
              for (let i = 0; i < data.length; i++) {
                if (that.data.userId == data[i].from_username) {
                  for (let j = 0; j < data[i].msgs.length; j++) {
                    that.setMsgBox(that.data.userId, data[i].msgs[j]);
                  }
                }
              }
            }
          });

        }).onFail(function (data) {
          wx.showToast({
            title: '请求超时',
            icon: 'fail',
            duration: 1500
          })
        })

      });
    })
  },


  initJim() {
    return new Promise((resolve, reject) => {
      JIM.init({
        "appkey": "00ca9e9d16207e781db439b4",
        "random_str": "abcdefghijk_123456789",
        "signature": signature,
        "timestamp": myDate
      }).onSuccess(function (data) {
        resolve(data)
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  topTab: function (e) {
    var dataId = e.currentTarget.id;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    this.setData({
      tabArr: obj
    })
  },

  showImgBox: function () {
    let showBox = !this.data.showImgAddBox;
    this.setData({
      showImgAddBox: showBox
    })
  },

  //关闭对话
  closeDialogue: function () {
    this.setData({
      userMsg: "",
    })
    //显示对话框
    let setDialogue = !this.data.showDialogue
    this.setData({
      showDialogue: setDialogue
    })
  },
  //初始化对话
  tellAnyOne: function (e) {
    wx.hideTabBar({
      animation: true //是否需要过渡动画
    })
    //显示对话框
    let setDialogue = !this.data.showDialogue
    this.setData({
      showDialogue: setDialogue
    })

    const that = this;

    this.setData({
      userMsg: "",
    })

    //调出本地储存的消息
    wx.getStorage({
      key: e.currentTarget.id,
      success: function (res) {
        that.setData({
          userMsg: res.data,
        })
      }
    })

    //设置信息
    this.setData({
      userId: e.currentTarget.id
    })
  },

  //发送消息
  submitMsg: function () {
    if (this.data.inputMsg) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });

      const that = this;
      //发送消息
      JIM.sendSingleMsg({
        'target_username': that.data.userId,
        'content': that.data.inputMsg,
        no_offline: false
      }).onSuccess(function (data, msg) {
        let sendMsg = [{
          "content": {
            "msg_body": {},
            "create_time": "",
            "toMsg": true
          }
        }];
        sendMsg[0].content.msg_body.text = that.data.inputMsg;
        sendMsg[0].content.create_time = myDate;

        //放入消息盒子
        that.setMsgBox(that.data.userId, sendMsg);
        wx.hideLoading();
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 1500
        })

        //清空input
        that.setData({
          inputMsg: ''
        })

        //医生端回复
        if (app.loginUser.role == "2") {
          const replyData = {};
          replyData.userImName = that.data.userId;
          replyData.doctorImName = app.userIMinfo.imUsername;
          fetch("/inquiryDoctor/Messages/replyTime", replyData, "POST").then(res => {});
        }

      }).onFail(function (data) {
        wx.showToast({
          title: '发送失败',
          icon: 'fail',
          duration: 1500
        })
      });

    }
  },

  // 获取input内部消息
  takeMsg: function (e) {
    this.setData({
      inputMsg: e.detail.value
    })
  },

  //保存用户收发信息
  setMsgBox: function (id, item) {
    const that = this;
    //把新信息添加到userMsg里
    let msgBox = that.data.userMsg

    for (let i = 0; i < item.length; i++) {
      item[i].content.create_time = app.modTime(item[i].content.create_time, "yyyy.mm.dd HH:mm:ss");
    }

    if (msgBox.length > 0) {
      msgBox = msgBox.concat(item)
    } else {
      msgBox = item
    }

    that.setData({
      userMsg: msgBox
    })

    console.log(that.data.userMsg)
    console.log(id)
    //把新得到的msgBos存到本地缓存
    wx.setStorage({
      key: id,
      data: msgBox
    })
  },

})